package com.java.hohenheim.springplatform.web.service.login;

import com.java.hohenheim.springplatform.data.model.account.LoginParams;
import com.java.hohenheim.springplatform.data.model.account.UserInfoModel;
import com.java.hohenheim.springplatform.data.model.account.wx.WXAppletSessionRespModel;
import com.java.hohenheim.springplatform.db.dao.AccountDAO;
import com.java.hohenheim.springplatform.db.entity.AccountEntity;
import com.java.hohenheim.springplatform.db.entity.AccountThirdAuthsEntity;
import com.java.hohenheim.springplatform.db.entity.AccountWithThirdEntity;
import com.java.hohenheim.springplatform.define.ResultCodes;
import com.java.hohenheim.springplatform.define.ThirdPlatformDefine;
import com.java.hohenheim.springplatform.define.WeChatResultCode;
import com.java.hohenheim.springplatform.exception.PlatformException;
import com.java.hohenheim.springplatform.snowflake.SnowflakeWorker;
import com.java.hohenheim.springplatform.web.service.WXService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author Hohenheim
 * @date 2020/8/11
 * @description 微信小程序
 */
@Component("wxAppletLogin")
@Slf4j
public class WXAppletLogin extends BaseLogin {
    @Autowired
    private WXService mWXService;
    @Autowired
    private AccountDAO mAccountDAO;
    @Resource(name = "UserId")
    private SnowflakeWorker mUserIdWorker;

    @Override
    public UserInfoModel login(LoginParams param) {
        WXAppletSessionRespModel sessionRespModel = mWXService.wechatAppletSession(param.getAccount());
        if(sessionRespModel.getErrCode() != WeChatResultCode.SUCCESS.getCode()) {
            //请求小程序授权 SESSION 失败
            String errMsg = WeChatResultCode.getDesc(sessionRespModel.getErrCode());
            throw new PlatformException(ResultCodes.LOGIN_FAIL.getCode(), errMsg);
        }

        //查询用户是否已经存在
        UserInfoModel userInfoModel;
        AccountWithThirdEntity withThirdEntity = mAccountDAO.getBaseMapper()
                .selectWithThirdByOpenId(ThirdPlatformDefine.WX.getCode(), sessionRespModel.getOpenId());

        //如果用户不存在，给用户创建账号
        try {
            if (null == withThirdEntity) {
                long userId = mUserIdWorker.nextId();

                AccountEntity accountEntity = new AccountEntity();
                accountEntity.setUserId(userId);
                accountEntity.setUserName("WX-" + userId);

                AccountThirdAuthsEntity thirdEntity = new AccountThirdAuthsEntity();
                thirdEntity.setUserId(userId);
                thirdEntity.setOpenId(sessionRespModel.getOpenId());
                thirdEntity.setUnionId(sessionRespModel.getUnionId());
                thirdEntity.setPlatform((short) ThirdPlatformDefine.WX.getCode());
                thirdEntity.setToken(sessionRespModel.getSessionKey());

                if(addThirdPlatformAccount(accountEntity, thirdEntity)) {
                    userInfoModel = new UserInfoModel();
                    BeanUtils.copyProperties(accountEntity, userInfoModel);
                }
                else {
                    log.error("微信登录", "用户信息入库失败");
                    throw new PlatformException(ResultCodes.LOGIN_FAIL);
                }
            }
            else {
                userInfoModel = new UserInfoModel();
                BeanUtils.copyProperties(withThirdEntity, userInfoModel);
            }
        }
        catch (BeansException e) {
            log.error("微信登录", "登录失败，用户信息创建失败：" + e.getMessage(), e);
            throw new PlatformException(ResultCodes.LOGIN_FAIL);
        }

        return userInfoModel;
    }
}